package gamer.servlet;

import gamer.Bean.LinkBean;
import gamer.data.DatabaseOpera;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;

public class PinyinLink extends HttpServlet {
    HashMap<String, String> idiom, word;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        LinkBean pinyinLink = (LinkBean) req.getSession().getAttribute("pinyinLink");
        if (pinyinLink == null) {
            pinyinLink = new LinkBean();
            req.setAttribute("pinyinLink", pinyinLink);
        }
        DatabaseOpera dbs = new DatabaseOpera();
        idiom = dbs.mysqlQuery("*", "idiom", "idiom = '" + req.getParameter("idiom") + "';");
        System.out.println(idiom.toString());
        if (!idiom.isEmpty()) {
            if (pinyinLink.getIdiomLink().isEmpty() || Objects.equals(pinyinLink.getIdiomLink().getLast().get("last_pinyin"), idiom.get("first_pinyin"))) {
                pinyinLink.setIdiomLink(idiom);
                idiom=dbs.mysqlQuery("*", "idiom", "first_pinyin = '" + idiom.get("last_pinyin") + "'");
                if(idiom.isEmpty())
                    System.out.println("玩家获胜");
                else pinyinLink.setIdiomLink(idiom);
            } else System.out.println("接龙失败");
        } else System.out.println("成语不存在");
        req.getRequestDispatcher("jsp/game/pinyinLink.jsp").forward(req, resp);
    }
}
